extends StateBase

var battleField:BattleField
var moveTargetCellPos:Vector2
var currentCellPos:Vector2
var move
var path:Array
var moveSpeed


func enter():
	battleField = ownerNode.battleField
	moveTargetCellPos = ownerNode.moveTargetCell
	currentCellPos = ownerNode.data.battlePos
	move = ownerNode.data.getPropMove()
	if not ownerNode.data.battleIsEnemy:
		path = battleField.findPath(currentCellPos, moveTargetCellPos, move, BattleData.enemiesCellPosArr())
	else:
		path = battleField.findPath(currentCellPos, moveTargetCellPos, move, BattleData.herosCellPosArr())
	moveSpeed = battleField.entityMoveSpeed
	

func exit():
	pass


func run(delta):
	processMove(delta)
	

func processMove(delta):
	if path.size() <= 0: return
	
	var nextMoveCellPos = path[0]
	var nextMovePos = battleField.cell2PosCenter(nextMoveCellPos) 
	var currentPos = ownerNode.position
	var tentativeMoveDistance = moveSpeed * delta
	var moveDir = nextMoveCellPos - currentCellPos
	var remainDistance = currentPos.distance_to(nextMovePos)
	
	if moveDir != Vector2.ZERO:
		if moveDir.x == -1:
			ownerNode.data.battleFace = "Left"
			ownerNode.animations.play("Walk" + ownerNode.data.battleFace)
		elif moveDir.x == 1:
			ownerNode.data.battleFace = "Right"
			ownerNode.animations.play("Walk" + ownerNode.data.battleFace)
		elif moveDir.y == -1:
			ownerNode.data.battleFace = "Up"
			ownerNode.animations.play("Walk" + ownerNode.data.battleFace)
		elif moveDir.y == 1:
			ownerNode.data.battleFace = "Down"
			ownerNode.animations.play("Walk" + ownerNode.data.battleFace)
	
	if tentativeMoveDistance >= remainDistance:
		ownerNode.position += moveDir * remainDistance
		path.pop_front()
		currentCellPos = nextMoveCellPos 
		if path.size() <= 0:
			ownerNode.data.battlePos = moveTargetCellPos
			ownerNode.stateMachine.removeState(name)
			ownerNode.stateMachine.addState(Consts.battleEntityStateCommand)
			ownerNode.onMoveArriveTarget()
	else:
		ownerNode.position += moveDir * tentativeMoveDistance
		
	
	
